<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Echo</title>
	<style>
		body {
			margin: 0
		}
		::-webkit-scrollbar {
			width: 8px;
			height: 8px;
		}
		::-webkit-scrollbar-thumb {
			/*滚动条滑块*/
			border-radius: 8px;
			background: rgba(0, 0, 0, .5);
		}
		::-webkit-scrollbar-track {
			border-radius: 8px;
			background: rgba(0, 0, 0, .1);
		}

		.flex-item {
			flex: 1;
		}
		.container {
			display: flex;
			flex-direction: column;
			height: 100vh;
		}
		.container header {
			line-height: 2em;
			text-align: center;
			border-bottom: 1px solid #f6f6f6;
			color: #ddd;
		}
		.container .list {
			box-sizing: border-box;
			height: 100%;
			padding: 1px;
			overflow-y: auto;
			word-break: break-all;
		}
		.container .footer {
			display: flex;
			border-top: 1px solid #f6f6f6;
		}
		.form-item {
			line-height: 1;
			padding: 1em 1em 0.8em;
			border: none;
		}
		.form-item:focus {
			outline: none;
		}

		.pull-right {
			text-align: right;
		}
		.msg {
			display: inline-block;
			margin: 8px 1em;
			padding: 8px;
			min-width: 160px;
			border: 1px solid #eee;
			border-radius: 4px;
			box-shadow: 0 0 3px 3px #eee;
			color: #333;
		}
		.notice {
			border: none;
			display: block;
			color: chocolate;
			text-align: center;
		}
	</style>
</head>
<body>
	<div class="container">
		<header>Echo</header>
		<main class="flex-item">
			<div class="list"></div>
		</main>
		<form class="footer">
			<input type="text" class="form-item flex-item">
			<button type="submit" class="form-item">Send</button>
		</form>
	</div>
	<script src="/socket.io/socket.io.js"></script>
	<script>
	const Max = 50
	const MsgList = []

	const socket = io(location.origin);
	socket.on('welcome', render);
	socket.on('message', render);

	function render(data) {
		if (MsgList.length > Max) {
			MsgList.pop()
		}
		MsgList.push(data)

		var html = MsgList.map(data => {
			let msg = String(data.msg).replace('/</g', '&lt;').replace('/>/g', '&gt;')
			if (!data.id) {   // 系统消息
				return `<div class="notice"><p>${msg}</p></div>`
			}
			if (data.id === socket.id) {
				return `<div class="pull-right"><div class="msg">${msg}</div></div>`
			} else {
				return `<div><div class="msg">${msg}</div></div>`
			}
		}).join('')
		document.querySelector('.list').innerHTML = html
	}

	let dom = document.querySelector('.footer input')
	document.querySelector('.footer').addEventListener('submit', function(e) {
		e.preventDefault()
		let val = dom.value
		if (/\S/.test(val)) {
			dom.value = ''
			socket.emit('post', val)
		}
		dom.focus()
	})
	</script>
</body>
</html>
